package HelloServiceDo

import (
	"context"
	"github.com/go-redis/redis/v8"
	"goGrpc/helloService/DataBaseUtils"
	"log"
	"time"
)

func RedisTest() {
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()
	pong, err := DataBaseUtils.RedisConnection.Ping(ctx).Result()
	if err != nil {
		log.Fatalf("Redis连接池工作异常！err:%v\n", err)
	}
	log.Println("redis链接状态", pong, err)

	err = DataBaseUtils.RedisConnection.Set(ctx, "feekey", "examples", time.Second*5).Err()
	if err != nil {
		panic(err)
	}
	log.Println("redis插入数据完成!")
	val, err := DataBaseUtils.RedisConnection.Get(ctx, "feekey").Result()
	if err != nil {
		panic(err)
	}
	log.Println("redis第一次查询value:", val)
	val, err = DataBaseUtils.RedisConnection.Get(ctx, "feekey").Result()
	if err != nil {
		panic(err)
	}
	log.Println("redis第二次次查询value:", val)
	log.Println("执行10s定时器")
	timer := time.NewTimer(time.Second * 10)
	<-timer.C
	log.Println("10s定时器执行完毕")
	val, err = DataBaseUtils.RedisConnection.Get(ctx, "feekey").Result()
	if err == redis.Nil {
		log.Printf("redis key值已经失效，失效查询value: %v \n", val)
	} else if err != nil {
		log.Printf("redis异常: %v \n", err)
	} else {
		log.Printf("redis key值并未失效，失效查询value: %v \n", val)
	}

	val2, err := DataBaseUtils.RedisConnection.Get(ctx, "feekey2").Result()
	if err == redis.Nil {
		log.Printf("feekey does not exist \n")
	} else if err != nil {
		log.Printf("redis异常: %v \n", err)
	} else {
		log.Printf("feekey: %v \n", val2)
	}
}
